import { Router, Common } from "../../utils/common.js";
import { RemoteDataService } from '../../utils/remoteDataService.js';
import { TokenStorage, WeRunStorage, UserStorage } from "../../utils/storageSevice.js";

const progWidth = 450
Page({

  data: {
    weRunStep: 0,
    pet: {},
    pics: [],
    feeds: [],
    isCollect: 0,
    picLiker: 0,
    picLikeCount: 0,
    isShowCollect: true,
    progWidth,
    progInWidth: 0,
    levelUp: 10000
  },
  onLoad: function (options) {
    let that = this
    let token = TokenStorage.getData()
    if (!token){
      wx.showNavigationBarLoading()
      wx.login({
        success: res => {
          if (res.code) {
            RemoteDataService.wxLogin({ jsCode: res.code }).then(result => {
              if (result && result.code == "000") {
                TokenStorage.setData(result.accessToken);
                that.loadPetDet(options)
                that.getWeRunData()
              }
            }).catch(err => {
            })
          }
          wx.hideNavigationBarLoading()
        },
        fail: err => {
          wx.hideNavigationBarLoading()
          console.log(err);
        }
      })
    }else{
      that.loadPetDet(options)
      that.getWeRunData()
    }
  },
  loadPetDet: function (options){
    let that = this
    if (options && options.petId) {
      let params = {
        petId: options.petId
      }
      wx.showNavigationBarLoading()
      RemoteDataService.getUserPetDet(params).then(result => {
        if (result && result.code == "000") {
          wx.setNavigationBarTitle({ title: result.pet.petName })
          let userInfo = UserStorage.getData()
          let isShowCollect = true;
          if (userInfo.userId == result.pet.userid) {
            isShowCollect = false
          }
          let nextLevelNeed = result.pet.nextLevelNeed
          let tmpWidth = result.pet.totalEnergy / nextLevelNeed * progWidth
          that.setData({
            pet: result.pet,
            pics: result.pics,
            feeds: result.feeds,
            isCollect: result.isCollect,
            picLiker: result.picLiker,
            picLikeCount: result.pet.picLikeCount,
            isShowCollect: isShowCollect,
            progInWidth: tmpWidth,
            levelUp: nextLevelNeed
          })
        }
        wx.hideNavigationBarLoading()
      }).catch(err => {
        wx.hideNavigationBarLoading()
      })
    }
  },
  navToPetPic: function(){
    let that = this
    let params = {
      petId: that.data.pet.id,
      userId: that.data.pet.userid,
      petName: that.data.pet.petName,
      picLiker: that.data.picLiker,
      picLikeCount: that.data.picLikeCount
    }
    Router.navigateTo("../dogpic/dogpic", params);
  },
  navToSomeonePet: function (e) {
    let currUserId = e.currentTarget.dataset.userid
    let userInfo = UserStorage.getData()
    if (currUserId == userInfo.userId){
      wx.switchTab({
        url: "/pages/index/index"
      })
    }else{
      let params = {
        userId: currUserId
      }
      Router.navigateTo("../doglist/doglist", params)
    }

  }, 
  navToMyPet: function(){
    wx.switchTab({
      url: '../index/index'
    })
  },
  navToPetEdit: function () {
    let that = this
    let petVali = {
      petNameOk: true,
      sexOk: true,
      birthdayOk: true,
      weightOk: true,
      featureOk: true,
      neuOk: true,
      avatarOk: true,
      breedOk: true
    }
    that.data.pet.avatarTmp = that.data.pet.avatar
    let params = {
      pet: JSON.stringify(that.data.pet),
      petVali: JSON.stringify(petVali)
    }
    Router.navigateTo("../dogedit/dogedit", params);
  },
  feedPet: function(){
    let that = this
    let params = {
      petId: that.data.pet.id,
      userId: that.data.pet.userid
    }
    wx.showNavigationBarLoading()
    RemoteDataService.feedPet(params).then(result => {
      if (result && result.code == "000") {
        if (result.hasFeed && result.hasFeed==1){
          Common.myToast("今天遛过狗了");
        }else{
          if (result.feedVal>0){
            Common.myToast("遛狗：" + result.feedVal + "m");
            setTimeout(function () {
              Router.redirectTo("../dogdet/dogdet", { petId: that.data.pet.id })
            }, 2000)
          } else if (result.feedVal==0){
            Common.myToast("今天已遛三次狗了");
          }
        }
      }
      wx.hideNavigationBarLoading()
    }).catch(err => {
      wx.hideNavigationBarLoading()
    })
  },
  collectPet: function () {
    let that = this
    let collectVal = that.data.isCollect
    if (that.data.isCollect==0){
      collectVal = 1
    }else{
      collectVal = 0
    }
    let params = {
      petId: that.data.pet.id,
      userId: that.data.pet.userid,
      isCollect: collectVal
    }
    wx.showNavigationBarLoading()
    RemoteDataService.CollectPet(params).then(result => {
      if (result && result.code == "000") {
        that.setData({
          isCollect: collectVal
        })
        if (collectVal==1){
          Common.myToast("收藏成功");
        }else{
          Common.myToast("取消收藏成功");
        }
      }
      wx.hideNavigationBarLoading()
    }).catch(err => {
      wx.hideNavigationBarLoading()
    })
  },
  getWeRunData: function () {
    let currentTime = new Date().getTime()
    let wxRunLastTime = WeRunStorage.getData();
    console.log("距离上次获取wxRun时间：" + ((currentTime - wxRunLastTime) / 1000));
    if (!wxRunLastTime || ((currentTime - wxRunLastTime) / 1000) > 3600) {//1 hour per time
      this.checkWeRunSettingsStatus()
    }
  },
  // onShow: function () {
  //   let currentTime = new Date().getTime()
  //   let wxRunLastTime = WeRunStorage.getData();
  //   console.log("距离上次获取wxRun时间：" + ((currentTime - wxRunLastTime) / 1000));
  //   if (!wxRunLastTime || ((currentTime - wxRunLastTime) / 1000) > 3600){//1 hour per time
  //     this.checkWeRunSettingsStatus()
  //   }
  // },
  checkWeRunSettingsStatus: function () {//检查授权状态
    var that = this;
    getSet().then(result => {
      return nogetSet();
    }).then(results => {

    }, function (err) {
      console.log("网络失败");
    })

    //查看用户是否第一次授权授权
    function getSet() {
      var sets = new Promise((resolve, reject) => {
        //检查授权情况
        wx.getSetting({
          success: function (res) {
            //获取WeRun
            wx.getWeRunData({
              success: function (res) {
                if (res.encryptedData && res.iv){
                  RemoteDataService.getWeRunStep({ encryptedData: res.encryptedData, iv: res.iv }).then(result => {
                    if (result && result.code=="000") {
                      console.log("wxRun step==="+result.wxRun.step)
                      WeRunStorage.setData(new Date().getTime());
                    }
                  }).catch(err => {
                    that.setData({
                      loading: false
                    });
                  })
                }
              },
              fail: function (err) {
                wx.showModal({
                  title: '提示',
                  content: '未开通微信运动，请关注“微信运动”公众号后重试',
                  showCancel: false,
                  confirmText: '知道了，汪'
                })
              }
            })
          },
          fail: function (err) {
            reject(err);
          }
        });
      });
      return sets;
    };
    // 用户未授权的情况下，不断要求用户授权
    function nogetSet() {
      var nosets = new Promise((resolve, reject) => {
        wx.showModal({
          title: '用户未授权',
          content: '亲，授权“微信运动”后，就可以遛一遛狗狗啦！',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  console.log(res)
                },
                fail: function (err) {
                  console.log(err);
                }
              })
            }
          }
        })
      });
      return nosets;
    }
  }
  
})